<template>
    <div class="user-profile-page">
      <van-nav-bar
        left-arrow
        @click-left="$router.back()"
        title="个人信息"
      ></van-nav-bar>
      <van-cell-group>
      <van-cell is-link title="头像" center @click="uploadImg">
        <van-image slot="default" fit="cover" round :src="user.photo" />
      </van-cell>
      <van-cell is-link title="昵称"
      :value="user.name || '未填写'"
      @click="userNameInfo"
      />
    </van-cell-group>
    <van-cell-group style="margin-top: 12px">
      <van-cell is-link title="性别"
      @click="showGender = true"
      :value="user.gender === 0 ? '男' : '女'" />
      <van-cell is-link title="生日"
      @click="openBirthdayPopup"
      :value="user.birthday || '未填写'" />
    </van-cell-group>
      <div class="logout" @click="logout">
        <span>退出登录</span>
      </div>
      <input type="file" @change="handChange" style="display: none;" ref="fileRef">
      <van-popup class="my-popup" v-model="showName" position="right">
        <van-nav-bar
          left-arrow
          @click-left="showName = false"
          @click-right="saveName()"
          right-text="保存"
          title="修改昵称"
        />
        <van-field v-model="name"></van-field>
      </van-popup>
        <!-- 修改性别 -->
    <van-action-sheet
      v-model="showGender"
      :actions="[
        { name: '男', value: 0 },
        { name: '女', value: 1 },
      ]"
      @select="saveGender"
      cancel-text="取消"
    />
     <!-- 修改生日 -->
     <van-popup v-model="showBirthday" position="bottom">
      <van-datetime-picker
        v-model="birthday"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showBirthday = false"
        @confirm="saveBirthday"
      />
    </van-popup>
    </div>
  </template>

<script>
import { getUserProfile, updateUserProfile } from '@/api/user'
import dayjs from 'dayjs'
export default {
  name: 'UserProfilePage',
  data () {
    return {
      user: {},
      showName: false,
      showGender: false,
      name: '',
      // 修改生日
      showBirthday: false,
      birthday: new Date(),
      minDate: new Date('1960-01-01'),
      maxDate: new Date()
    }
  },
  created () {
    this.getUserProfile()
  },
  methods: {
    async getUserProfile () {
      const [err, res] = await getUserProfile()
      if (err) return this.$toast.fail('信息获取失败，请重试')
      this.user = res.data.data
    },
    async logout () {
      await this.$dialog.confirm({
        title: '退出登录',
        message: '确定退出登录?'
      })
      this.$store.commit('user/REMOVE_TOKEN')
      
      this.$router.push('/')
      this.$toast.fail('退出登录')
    },
    uploadImg () {
      this.$refs.fileRef.click()
    },
    async handChange (e) {
      const files = e.target.files[0]
      if (!files) return
      const formData = new FormData()
      formData.append('photo', files)
      const [err, res] = await getUserProfile(formData)
      if (err) this.$toast.files('上传失败')
      else {
        this.user.photo = res.data.data.photo
        this.$toast.success('修改成功')
      }
      e.target.value = null
    },
    async saveName () {
      if (!this.name) return this.$toast('请输入昵称')
      const [err] = await updateUserProfile({ name: this.name })
      if (err) return this.$toast.fail('更新失败')
      // 更新单元格中的昵称
      this.user.name = this.name
      this.showName = false
      this.$toast.success('更新成功')
    },
    userNameInfo () {
      this.showName = true
      this.name = this.user.name
    },
    // 修改用户性别
    async saveGender (item) {
      const [err] = await updateUserProfile({ gender: item.value })
      if (err) return this.$toast.fail('更新失败')
      this.user.gender = item.value
      this.showGender = false
      this.$toast.success('更新成功')
    },
    // 打开日期选择器
    openBirthdayPopup () {
      this.showBirthday = true
      // 给日期控件赋值，当前用户的生日
      this.birthday = new Date(this.user.birthday)
    },
    async saveBirthday () {
      // 转换格式
      const date = dayjs(this.birthday).format('YYYY-MM-DD')
      const [err] = await updateUserProfile({ birthday: date })
      if (err) return this.$toast.fail('更新失败')
      this.user.birthday = date
      this.showBirthday = false
      this.$toast.success('更新成功')
    }
  }
}
</script>

  <style lang="less" scoped>
  .my-popup {
    width: 100%;
    height: 100%;
    /deep/ .van-nav-bar__text {
      color: @geek-color;
    }
    /deep/ .van-field__control {
      background: @geek-gray-color;
      padding: 10px;
      border-radius: 4px;
    }
  }
  .user-profile-page {
    background: #f8f8f8;
    .van-image {
      display: block;
      float: right;
      width: 30px;
      height: 30px;
    }
    .van-cell__title {
      width: 50px;
      flex: none;
    }
  }
  .logout {
    text-align: center;
    position: absolute;
    left: 0;
    bottom: 30px;
    width: 100%;
    color: @geek-color;
  }
  </style>
